package com.mojian.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mojian.entity.SysNotifications;
import com.mojian.service.CommentService;
import com.mojian.utils.NotificationsUtil;
import com.mojian.utils.SensitiveUtil;
import com.mojian.vo.comment.CommentListVo;
import com.mojian.entity.SysComment;
import com.mojian.mapper.SysCommentMapper;
import com.mojian.utils.IpUtil;
import com.mojian.utils.PageUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {

    private final SysCommentMapper sysCommentMapper;

    private final NotificationsUtil notificationsUtil;

    @Override
    public IPage<CommentListVo> getComments(Integer articleId, String sortType) {
        IPage<CommentListVo> page = sysCommentMapper.getComments(PageUtil.getPage(), articleId, sortType);
        
        // 获取当前登录用户ID，未登录则为null
        Long userId = null;
        try {
            if (StpUtil.isLogin()) {
                userId = StpUtil.getLoginIdAsLong();
            }
        } catch (Exception e) {
            // 未登录或获取用户ID失败，忽略
        }
        
        // 获取所有子评论，并标记当前用户的点赞状态
        final Long finalUserId = userId; // Make userId effectively final for lambda
        
        page.getRecords().forEach(commentListVo -> {
            // 设置当前用户是否点赞
            if (finalUserId != null) {
                Boolean isLiked = sysCommentMapper.getUserIsLike(commentListVo.getId().longValue(), finalUserId.intValue());
                commentListVo.setIsLiked(isLiked != null && isLiked);
            }
            
            // 获取子评论
            List<CommentListVo> children = sysCommentMapper.getChildrenComment(commentListVo.getId());
            if (finalUserId != null && children != null) {
                // 标记子评论的点赞状态
                children.forEach(child -> {
                    Boolean isLiked = sysCommentMapper.getUserIsLike(child.getId().longValue(), finalUserId.intValue());
                    child.setIsLiked(isLiked != null && isLiked);
                });
            }
            commentListVo.setChildren(children);
        });
        return page;
    }

    @Override
    public void add(SysComment sysComment) {

        String ip = IpUtil.getIp();
        sysComment.setIp(ip);
        sysComment.setIpSource(IpUtil.getIp2region(ip));
        sysComment.setUserId(StpUtil.getLoginIdAsLong());
        sysComment.setContent(SensitiveUtil.filter(sysComment.getContent()));

        sysCommentMapper.insert(sysComment);

        ThreadUtil.execAsync(() -> {
            //发送通知事件
            SysNotifications notifications = SysNotifications.builder()
                    .title(sysComment.getReplyUserId() != null ? "评论回复通知" : "新评论通知")
                    .message(sysComment.getContent())
                    .articleId(sysComment.getArticleId())
                    .isRead(0)
                    .type("comment")
                    .userId(sysComment.getReplyUserId())
                    .fromUserId(sysComment.getUserId())
                    .build();
            notificationsUtil.publish(notifications);
        });
    }

    @Override
    public Boolean like(Long commentId) {
        // 判断是否点赞
        int userId = StpUtil.getLoginIdAsInt();
        Boolean isLike = sysCommentMapper.getUserIsLike(commentId, userId);
        
        if (isLike) {
            // 点过则取消点赞
            sysCommentMapper.unLike(commentId, userId);
            sysCommentMapper.updateUnlikeCount(commentId);
        } else {
            // 点赞并增加点赞数
            sysCommentMapper.like(commentId, userId);
            sysCommentMapper.updateLikeCount(commentId);
            
            // 获取评论所有者，发送通知
            SysComment comment = sysCommentMapper.selectById(commentId);
            
            // 异步发送点赞通知
            ThreadUtil.execAsync(() -> {
                if (comment != null && !comment.getUserId().equals(StpUtil.getLoginIdAsLong())) {
                    SysNotifications notifications = SysNotifications.builder()
                            .title("评论点赞通知")
                            .articleId(comment.getArticleId())
                            .isRead(0)
                            .type("like")
                            .userId(comment.getUserId()) // 通知接收人
                            .fromUserId(StpUtil.getLoginIdAsLong()) // 点赞人
                            .build();
                    notificationsUtil.publish(notifications);
                }
            });
        }
        return true;
    }
}
